
import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Calendar, Clock, BookOpen, Bell, Plus, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";

interface StudyBlock {
  id: string;
  subject: string;
  day: string;
  startTime: string;
  endTime: string;
  reminders: boolean;
}

interface StudyScheduleModalProps {
  onClose: () => void;
}

const daysOfWeek = [
  'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
];

const timeSlots = [
  '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00',
  '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00',
  '20:00', '21:00', '22:00'
];

const subjects = [
  'Mathematics', 'English', 'Science', 'History', 'Geography',
  'Foreign Language', 'Arts', 'Computer Science', 'Other'
];

export function StudyScheduleModal({ onClose }: StudyScheduleModalProps) {
  const [isOpen, setIsOpen] = useState(true);
  const [studyBlocks, setStudyBlocks] = useState<StudyBlock[]>([]);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newBlock, setNewBlock] = useState({
    subject: '',
    day: '',
    startTime: '',
    endTime: '',
    reminders: true
  });

  const handleClose = () => {
    setIsOpen(false);
    onClose();
  };

  const handleAddBlock = () => {
    if (!newBlock.subject || !newBlock.day || !newBlock.startTime || !newBlock.endTime) return;

    // Check for time conflicts
    const hasConflict = studyBlocks.some(block => 
      block.day === newBlock.day &&
      ((newBlock.startTime >= block.startTime && newBlock.startTime < block.endTime) ||
       (newBlock.endTime > block.startTime && newBlock.endTime <= block.endTime) ||
       (newBlock.startTime <= block.startTime && newBlock.endTime >= block.endTime))
    );

    if (hasConflict) {
      alert('Time conflict detected! Please choose a different time slot.');
      return;
    }

    const block: StudyBlock = {
      id: Date.now().toString(),
      subject: newBlock.subject,
      day: newBlock.day,
      startTime: newBlock.startTime,
      endTime: newBlock.endTime,
      reminders: newBlock.reminders
    };

    setStudyBlocks([...studyBlocks, block]);
    setNewBlock({
      subject: '',
      day: '',
      startTime: '',
      endTime: '',
      reminders: true
    });
    setShowAddForm(false);
  };

  const deleteBlock = (blockId: string) => {
    setStudyBlocks(studyBlocks.filter(block => block.id !== blockId));
  };

  const getBlocksForDay = (day: string) => {
    return studyBlocks
      .filter(block => block.day === day)
      .sort((a, b) => a.startTime.localeCompare(b.startTime));
  };

  const generateSuggestions = () => {
    // Simple AI-powered suggestions based on current schedule
    const busyDays = studyBlocks.reduce((acc, block) => {
      acc[block.day] = (acc[block.day] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const leastBusyDay = daysOfWeek.reduce((min, day) => 
      (busyDays[day] || 0) < (busyDays[min] || 0) ? day : min
    );

    return [
      `Consider adding a focus session on ${leastBusyDay} - it's your least busy day`,
      'Try scheduling review sessions after each main study block',
      'Add short breaks between consecutive study sessions',
      'Consider morning sessions for better concentration'
    ];
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Calendar className="w-5 h-5 text-purple-600" />
            Study Schedule Assistant
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* Add New Study Block Form */}
          {showAddForm ? (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Add Study Block</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>Subject *</Label>
                    <Select value={newBlock.subject} onValueChange={(value) => setNewBlock({...newBlock, subject: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select subject" />
                      </SelectTrigger>
                      <SelectContent>
                        {subjects.map(subject => (
                          <SelectItem key={subject} value={subject}>{subject}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  
                  <div>
                    <Label>Day *</Label>
                    <Select value={newBlock.day} onValueChange={(value) => setNewBlock({...newBlock, day: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select day" />
                      </SelectTrigger>
                      <SelectContent>
                        {daysOfWeek.map(day => (
                          <SelectItem key={day} value={day}>{day}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>Start Time *</Label>
                    <Select value={newBlock.startTime} onValueChange={(value) => setNewBlock({...newBlock, startTime: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select start time" />
                      </SelectTrigger>
                      <SelectContent>
                        {timeSlots.map(time => (
                          <SelectItem key={time} value={time}>{time}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label>End Time *</Label>
                    <Select value={newBlock.endTime} onValueChange={(value) => setNewBlock({...newBlock, endTime: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select end time" />
                      </SelectTrigger>
                      <SelectContent>
                        {timeSlots.map(time => (
                          <SelectItem key={time} value={time}>{time}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="flex items-center space-x-2">
                  <Switch
                    id="reminders"
                    checked={newBlock.reminders}
                    onCheckedChange={(checked) => setNewBlock({...newBlock, reminders: checked})}
                  />
                  <Label htmlFor="reminders" className="flex items-center gap-2">
                    <Bell className="w-4 h-4" />
                    Enable reminders
                  </Label>
                </div>

                <div className="flex gap-2">
                  <Button onClick={handleAddBlock}>Add Study Block</Button>
                  <Button variant="outline" onClick={() => setShowAddForm(false)}>Cancel</Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            <Button onClick={() => setShowAddForm(true)} className="w-full">
              <Plus className="w-4 h-4 mr-2" />
              Add Study Block
            </Button>
          )}

          {/* Weekly Schedule View */}
          <div className="grid grid-cols-1 lg:grid-cols-7 gap-4">
            {daysOfWeek.map(day => (
              <Card key={day}>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm font-medium text-center">{day}</CardTitle>
                </CardHeader>
                <CardContent className="pt-0 space-y-2">
                  {getBlocksForDay(day).map(block => (
                    <div key={block.id} className="relative bg-purple-50 border border-purple-200 rounded-lg p-3">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="absolute top-1 right-1 h-6 w-6 p-0"
                        onClick={() => deleteBlock(block.id)}
                      >
                        <X className="w-3 h-3" />
                      </Button>
                      <div className="pr-6">
                        <div className="font-medium text-sm text-purple-900">{block.subject}</div>
                        <div className="text-xs text-purple-700 flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {block.startTime} - {block.endTime}
                        </div>
                        {block.reminders && (
                          <div className="text-xs text-purple-600 flex items-center gap-1 mt-1">
                            <Bell className="w-3 h-3" />
                            Reminders on
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                  {getBlocksForDay(day).length === 0 && (
                    <div className="text-center text-gray-400 text-sm py-4">
                      No sessions
                    </div>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>

          {/* AI Suggestions */}
          {studyBlocks.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <BookOpen className="w-5 h-5 text-blue-600" />
                  AI Suggestions
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {generateSuggestions().map((suggestion, index) => (
                    <div key={index} className="flex items-start gap-2">
                      <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0"></div>
                      <p className="text-sm text-gray-700">{suggestion}</p>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Schedule Summary */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Schedule Summary</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                <div>
                  <div className="text-2xl font-bold text-purple-600">{studyBlocks.length}</div>
                  <div className="text-sm text-gray-600">Study Blocks</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-blue-600">
                    {new Set(studyBlocks.map(b => b.day)).size}
                  </div>
                  <div className="text-sm text-gray-600">Active Days</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-green-600">
                    {new Set(studyBlocks.map(b => b.subject)).size}
                  </div>
                  <div className="text-sm text-gray-600">Subjects</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-orange-600">
                    {studyBlocks.filter(b => b.reminders).length}
                  </div>
                  <div className="text-sm text-gray-600">Reminders</div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </DialogContent>
    </Dialog>
  );
}
